package cn.mxz.xmu.restful.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 加密类，提供各种加密方法
 * 
 * @author chenmin <chenmin@mouge.wang>
 * @author kangbin <kangbin@mouge.wang>
 * @since 2015-03-09
 */
public final class Encrypt
{
	/**
	 * SHA1加密
	 * 
	 * @param msg
	 * @return
	 */
	public static String sha1(String msg)
	{
		return EncoderHandler.encode("SHA1", msg);
	}

	/**
	 * 十六进制转换成字符串
	 */
	public static String hex2Dec(String msg)
	{
		byte[] baKeyword = new byte[msg.length() / 2];
		try
		{
			for (int i = 0; i < baKeyword.length; i++)
			{
				baKeyword[i] = (byte) (0xff & Integer.parseInt(msg.substring(i * 2, i * 2 + 2), 16));
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		try
		{
			msg = new String(baKeyword, "utf-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 字符串转换成十六进制
	 */
	public static String dec2Hex(String msg)
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < msg.length(); i++)
		{
			int ch = msg.charAt(i);
			String s = Integer.toHexString(ch);
			sb.append(s);
		}
		return sb.toString();
	}

	/**
	 * 将字符串进行URLEncode加密
	 * 
	 * @param input
	 *            加密之前的字符串
	 * @return 加密之后的字符串
	 */
	public static String urlEncode(String input)
	{
		try
		{
			return URLEncoder.encode(input, "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 将字符串进行URLEncode解密
	 * 
	 * @param input
	 *            解密之前的字符串
	 * @return 解密之后的字符串
	 */
	public static String urlDecode(String input)
	{
		try
		{
			return URLDecoder.decode(input, "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return "";
	}

	public static void main(String[] args)
	{
		String urlEncode_userIdString = urlEncode("http://210.34.4.28/opac/item.php?marc_no=0003709805");
		String deHexString = dec2Hex(urlEncode_userIdString);
		
		System.out.println(deHexString);
		String pwd = hex2Dec(deHexString);
		System.out.println(urlDecode(pwd));

	}
}
